<?php
/**
 * Created by PhpStorm.
 * User: bill
 * Date: 2014/12/3
 * Time: 15:41
 */

class C错误堆栈
{

    private static $instance;
    //名字index的数组,包括位置:line和类:函数--'位置'
    //---'结果'  true false
    // --'原因'
    //---'消息'
    public $stack;
    private $data; //消息传递历史

    private function __construct()
    {
        $this->data = array();
    }

    public static function getInstance()
    {
        if (empty(self::$instance)) {
            self::$instance = new C错误堆栈();
        }

        return self::$instance;
    }

    public function get_data()
    {
        return $this->data;
    }

    /**
     * @param $data
     * @param bool $结果
     */
    public function set_data($data, $结果 = false)
    {
        $this->data = array("结果" => $结果);
        $this->data = array_merge($this->data, $data);
        $stack[] = $data;
    }

    public function get_stack()
    {
        return $this->stack;
    }

    public function  打印堆栈()
    {
        var_dump($this->stack);
    }

    /**
     * @assert() ==true;
     */
    public function  clear()
    {
        $this->data = null;
        $this->stack = null;
        return true;
    }

    //条件  array("false == $读商家结果","该商家不存在"
    //如果出错,写错误堆栈
    public function  条件校验($conditions =array()){
        foreach($conditions as $条件语句=>$错误消息){
            if(eval("return ".$条件语句) == false) {
                $this->set_data(array("消息" => $错误消息.$this->caller_info(1)));
                return false;
            }
        }
        return true;
    }


    //0 是自己, 1是调用者,以此类推
    public function caller_info($who = 1){
        $trace = debug_backtrace();
        $who++;


        if($who >= count($trace)) return "您查询的调用函数不存在";
        $class = $trace[$who]['class'];
        $func = $trace[$who]['function'];
        $file = $trace[$who]['file'];
        $line = $trace[$who]['line'];

        if ($file != '') $file = basename($file);
        $c = $file . ": ";
        $c .= ($class != '') ? ":" . $class . "->" : "";
        $c .= ($func != '') ? $func . "(): " : "";
        $c .= ($line != '')?$line."行":"";
        return($c);

    }




} 